package com.yupi.yupao.controller;

import cn.hutool.json.JSONObject;
import com.yupi.yupao.common.BaseContext;
import com.yupi.yupao.common.BaseResponse;
import com.yupi.yupao.common.ErrorCode;
import com.yupi.yupao.common.ResultUtils;
import com.yupi.yupao.exception.BusinessException;
import com.yupi.yupao.model.domain.Team;
import com.yupi.yupao.model.domain.User;
import com.yupi.yupao.model.vo.WxTokenVO;
import com.yupi.yupao.service.TeamService;
import com.yupi.yupao.service.UserService;
import io.swagger.annotations.Api;
import lombok.Data;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @Author: Peter
 * @Date: 2024-10-04-22:08
 * @Description: Pe
 */
@Api(tags = "微信订阅消息（一次性）")
@RestController
@Slf4j
@RequestMapping(value = "/wx/msg")
public class WxMsgSendController {
    //发送订阅消息
    //POST https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN

    /**
     * 微信发送订阅消息流程
     * 1.wx.requestSubscribeMessage 获取订阅权限
     * 2.授权后把请求发送到服务端
     * 3.需要推送的用户的openId
     * 4.获取access_token
     * 5.封装数据格式
     *   ：{
     *   "touser": "OPENID",
     *   "template_id": "TEMPLATE_ID",
     *   "page": "index",
     *   "data": {
     *       "name01": {
     *           "value": "某某"
     *       },
     *       "amount01": {
     *           "value": "￥100"
     *       },
     *       "thing01": {
     *           "value": "广州至北京"
     *       } ,
     *       "date01": {
     *           "value": "2018-01-01"
     *       }
     *   }
     * }
     * 6.调用接口推送订阅消息
     *   ：POST https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN
     *
     *
     *
     */

    @Resource
    private TeamService teamService;
    @Resource
    private UserService userService;

    @PostMapping("/send/{userId}&{teamId}")
    public BaseResponse<String> messageSend(@PathVariable("userId") Long userId, @PathVariable("teamId")  Long teamId){
        if(userId==null||teamId==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数错误");
        }


        WxTokenVO accessToken = teamService.getAccessToken();

        JSONObject body=new JSONObject();
        User user = userService.getById(userId);
        Team team = teamService.getById(teamId);
        body.set("touser",user.getOpenId());
        body.set("template_id","lZH_Sb4eub8CNfw3EoEJ2PaJAQOG2u7jvTrCL0U7TwM");
        body.set("page","/pages/home/home");
        body.set("miniprogramState","trial");
        JSONObject json=new JSONObject();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date current = new Date();
        json.set("thing1",new JSONObject().set("value",team.getName()));
        json.set("time7",new JSONObject().set("value",formatter.format(team.getCreateTime())));
        json.set("phrase6",new JSONObject().set("value","正在组队"));
        json.set("number5",new JSONObject().set("value", team.getMaxNum()));

        body.set("data",json);
        //发送
        String accessToken1= accessToken.getAccessToken();
        String post =  cn.hutool.http.HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken1, body.toString());
        log.info("请求成功，请求结果为："+post);


        return ResultUtils.success(post);
    }
}
